// pages/mine/record/petVaccination/index.js
const app = getApp()
import {formatDate} from '../../../../utils/util'

Page({

    data: {
        // pet 下拉框
                 // 下拉框选中数据
            choosedPetCondition: {
                nickname: '选择宠物', 
                id: '',
                type: ''
            },
            conditionPetVisible: false,
            conditionPetList: [{
                nickname: '选择所有',
                id:'0'
            },], // 下拉框数据
       
            // 疫苗类型下拉框
        conditionVaccinationVisible: false,
        // update和search都使用这个list
        conditionVaccinationList: [{
        }], // 下拉框数据
        choosedVaccinationCondition: {
            name: '请先选择宠物', 
            id: '',
            // description: ''
        },

        // 日期选择器
            tempDateBegin:formatDate(new Date()),
            tempDateEnd:formatDate(new Date()),
            timeNow: formatDate(new Date()),
    
        //   卡片
            bannerCurrent: 0, // 当前显示的banner,
            notUpdate:true,
            petVaccinationInfos:[],
          
           
        // update 表格数据
            tempFormData:'',
            conditionUpdateVaccinationVisible: false,
            choosedUpdateVaccinationCondition: {
                name: '请先选择宠物', 
                id: '',
                // description: ''
            },
            conditionUpdateVaccinationList:[],
            
        // 添加页面
            show: false,
            duration: 300,
            choosedAddTime:formatDate(new Date()),
            conditionAddPetVisible:false,
            conditionAddVaccinationVisible: false,
            conditionAddPetList: '',
            choosedAddPetCondition: {
                nickname: '选择宠物', 
                id: '-1`',
            },
            conditionAddVaccinationList:[],
            choosedAddVaccinationCondition:{
                name: '请先选择宠物', 
                id: '',
                // description: ''
            },
    },

    onLoad(){
        var that = this
        that.initializeDate()
    },

      // 保存添加
      saveAdd(e){
        const that = this
        let description = e.detail.value.description
    
        // 判空, 不想做
    
        wx.request({
          url: app.globalData.prefixUrl +'/chong/pet/vaccinate',
          data:{
            userId: app.globalData.userId,
            petId: that.data.choosedAddPetCondition.id,
            vaccinateId: that.data.choosedAddVaccinationCondition.id,
            vaccinateName: that.data.choosedAddVaccinationCondition.name,
            vaccinateTime: that.data.choosedAddTime,
            description,
          },
          method:"POST",
          header:{
            'Content-type': "application/x-www-form-urlencoded"
          },
          success(e){
              console.log("添加记录成功: ",e)
              that.searchSubmit()
          },
        })
    
        that.setData({
            show: false
        })
    
      },
    

      // 添加
    popAddContainer(){
        // 弹出page-container
        let duration = this.data.duration
        this.setData({
            show: true,
            duration
        })
    },
    onAddPetChnageCondition(e){
        var that = this
        const list = that.data.conditionAddPetList
        list.forEach(item => {
            if (item.id === e.currentTarget.dataset.id) {
                item.select = true
                that.getPetRelatedVaccination(item.type)
                that.setData({
                    'choosedAddPetCondition.nickname': item.nickname,
                    'choosedAddPetCondition.type': item.type,
                    'choosedAddPetCondition.id': item.id,
                })
            } else {
                item.select = false
            }
        })
        that.setData({
            conditionAddPetList: list
        })
    },
    showAddPetCondition() {
        this.setData({
            conditionAddPetVisible: !this.data.conditionAddPetVisible
        })
    },
    // 疫苗类型下拉框
    onAddVaccinationChnageCondition(e) {
        const list = this.data.conditionAddVaccinationList
        list.forEach(item => {
            if (item.id === e.currentTarget.dataset.id) {
                item.select = true
                this.setData({
                    'choosedAddVaccinationCondition.name': item.name,
                    'choosedAddVaccinationCondition.id': item.id,
                    // 'choosedVaccinationCondition.description': item.description
                })
            } else {
                item.select = false
            }
        })
        this.setData({
            conditionAddVaccinationList: list
        })
    },
    showAddVaccinationCondition() {
        this.setData({
            conditionAddVaccinationVisible: !this.data.conditionAddVaccinationVisible
        })
    },
    formAddChangeData(e){
        var that = this
        console.log("当前编辑选中时间: ", e.detail.value)
        that.setData({ 
          choosedAddTime: e.detail.value,
      });
    },

    // 编辑
    updatePetVaccination(){
        var that  = this
        let tempFormData = that.data.petVaccinationInfos[that.data.bannerCurrent]
        console.log("tempFormData: ",tempFormData)
        that.getPetRelatedVaccination(tempFormData.type)
        that.setData({
            notUpdate: false,
            tempFormData,
        })
    },
     // 疫苗类型下拉框
     onUpdateVaccinationChnageCondition(e) {
        const list = this.data.conditionUpdateVaccinationList
        list.forEach(item => {
            if (item.id === e.currentTarget.dataset.id) {
                item.select = true
                this.setData({
                    'choosedUpdateVaccinationCondition.name': item.name,
                    'choosedUpdateVaccinationCondition.id': item.id,
                    // 'choosedVaccinationCondition.description': item.description
                })
            } else {
                item.select = false
            }
        })
        this.setData({
            conditionUpdateVaccinationList: list
        })
    },
    showUpdateVaccinationCondition() {
        this.setData({
            conditionUpdateVaccinationVisible: !this.data.conditionUpdateVaccinationVisible
        })
    },
    formChangeData(e){
        var that = this
        console.log("当前编辑选中时间: ", e.detail.value)
        that.setData({ 
          'tempFormData.vaccinateTime':e.detail.value,
      });
    },

    // 取消编辑
    cancelUpdate(){
        var that = this
        that.setData({
            notUpdate: true,
        })
    },
    // 保存编辑 
    saveUpdate(e){
        var that = this
        let tempFormData = that.data.tempFormData
        let formData=e.detail.value;
        
        wx.request({
          url: app.globalData.prefixUrl + '/chong/pet/vaccinate/' + tempFormData.id,
          data:{
              id: tempFormData.id,
              vaccinateId: that.data.choosedUpdateVaccinationCondition.id,
              vaccinateName: that.data.choosedUpdateVaccinationCondition.name,
              description: formData.description,
              vaccinateTime: tempFormData.vaccinateTime
          },
          method:"PUT",
          header:{
            'Content-type': "application/x-www-form-urlencoded"
          },
          success(e){
              console.log("record:"+tempFormData.id+"数据更新成功. ", e)
              that.searchSubmit()
          }
        })
    },


    // 删除
    delPetVaccinationInfo(){
    var that = this
        wx.showModal({
        title: '提示',
        content: '确定删除该记录吗?',
        cancelText: '取消',
        confirmText: '确认',
        success: res => {
            if (res.confirm) {
            wx.request({
                url: app.globalData.prefixUrl + '/chong/pet/vaccinate/' + that.data.petVaccinationInfos[that.data.bannerCurrent].id,
                method:"DELETE",
                success(e){
                    console.log("记录 "+that.data.petVaccinationInfos[that.data.bannerCurrent].id+ " 删除成功")
                    let petVaccinationInfos = that.data.petVaccinationInfos
                    petVaccinationInfos.splice(that.data.bannerCurrent, 1)
                    that.setData({
                        petVaccinationInfos
                    })
                    if (petVaccinationInfos.length == 0) {
                    that.setData({
                        'petVaccinationInfos[0].noInfo': '没有符合要求的记录',
                        'petVaccinationInfos[0].id': 0,
                        })
                    }
                },
                fail(e){
                    console.log("记录 "+that.data.petVaccinationInfos[that.data.bannerCurrent].id+ " 删除失败")
                }
                })
            }
        }
        })
    
    },
    

    // 搜索
    searchSubmit(e){
        var that = this

        let petId = that.data.choosedPetCondition.id
        if (petId <= 0 || petId == null) {
            petId = that.data.conditionPetList[0].id
        }
        let vaccinateId = that.data.choosedVaccinationCondition.id
        if (vaccinateId <= 0 || vaccinateId == null) {
            vaccinateId = ''
        }
         // 判空, 不想做

         wx.request({
            url: app.globalData.prefixUrl + '/chong/pet/vaccinate/query',
            data:{
              userId: app.globalData.userId,
              petId,
              vaccinateId,
              // 生病时间 范围
              beginTime: that.data.tempDateBegin,
              endTime: that.data.tempDateEnd
            },
            method:"GET",
            success(e){
                console.log("search的宠物信息:", e)
                if (e.data != null && e.data != '') {
                    // 按照petId, 将pet信息插入到petVaccinationInfos里面
                    let petVaccinationInfos = e.data
                    let petId
                    for (let pet of that.data.conditionPetList) {
                        petId = pet.id
                        for (let petVa of petVaccinationInfos) {
                            if (petId == petVa.petId) {
                                petVa.petNickname = pet.nickname
                                petVa.type = pet.type
                                petVa.petPhoto = pet.petPhoto
                            }
                        }
                    }
                  that.setData({
                    petVaccinationInfos,
                      notUpdate: true,
                      show: false,
                      bannerCurrent: 0,
                  })
                } else {
                that.setData({
                  'petVaccinationInfos[0].noInfo': '没有符合要求的记录',
                  'petVaccinationInfos[0].id': 0,
                   notUpdate: true,
                   show: false,
                   bannerCurrent: 0,
                })
              }
            }
            
          })
    },
    // 搜索宠物下拉框  改变查询项
    onPetChnageCondition(e) {
        var that = this
        const list = this.data.conditionPetList
        const choosedPetId = e.currentTarget.dataset.id
        list.forEach(item => {
            if (item.id === choosedPetId) {
                item.select = true
                
                // 改变下拉框里的疫苗种类
                that.getPetRelatedVaccination(item.type)

                that.setData({
                    'choosedPetCondition.nickname': item.nickname,
                    'choosedPetCondition.type': item.type,
                    'choosedPetCondition.id': item.id
                })
            } else {
                item.select = false
            }
        })
        if (e.currentTarget.dataset.id == 0) {
            that.setData({
                'choosedPetCondition.nickname': '选择宠物',
                'choosedPetCondition.type':'',
                'choosedPetCondition.id': '0'
            })
        }
        that.setData({
            conditionPetList: list
        })
    },
    showPetCondition() {
        this.setData({
            conditionPetVisible: !this.data.conditionPetVisible
        })
    },
    // 疫苗类型下拉框
    onVaccinationChnageCondition(e) {
        const list = this.data.conditionVaccinationList
        list.forEach(item => {
            if (item.id === e.currentTarget.dataset.id) {
                item.select = true
                this.setData({
                    'choosedVaccinationCondition.name': item.name,
                    'choosedVaccinationCondition.id': item.id,
                    // 'choosedVaccinationCondition.description': item.description
                })
            } else {
                item.select = false
            }
        })
        // if (e.currentTarget.dataset.id == 0) {
        //     this.setData({
        //         'choosedVaccinationCondition.name': '请先选择宠物',
        //         'choosedVaccinationCondition.id': '',
        //         'choosedVaccinationCondition.description': ''
        //     })
        // }
        this.setData({
            conditionVaccinationList: list
        })
    },
    showVaccinationCondition() {
        this.setData({
            conditionVaccinationVisible: !this.data.conditionVaccinationVisible
        })
    },
        // date picker
    changeDateBegin(e){
        var that = this
        console.log("当前Begin选中时间: ", e.detail.value)
        that.setData({ 
            'tempDateBegin':e.detail.value,
        });
    },
    changeDateEnd(e){
        var that = this
        console.log("当前End选中时间: ", e.detail.value)
        that.setData({ 
            'tempDateEnd':e.detail.value,
        });
    },
    
    
  // 卡片滑动+翻转
    // 滑动
    bannerSwiper(e) {
        const that = this, 
        bannerCurrent = e.detail.current;
        that.setData({
        bannerCurrent,
        })
        console.log("当前bannder: "+bannerCurrent+"\t是否是正面: "+that.data.notUpdate)
    },

    // 根据宠物种类获取对应疫苗信息
    getPetRelatedVaccination(petType){
        var that = this

        if (petType == '' || petType == null) {
            let tmp = {}
            tmp.id = '0',
            // tmp.description = ''
            tmp.name = '选择所有'
             // update页面
             if (!that.data.notUpdate) {
                that.setData({
                    choosedUpdateVaccinationCondition: tmp,
                    conditionUpdateVaccinationList:''
                })
              } else if (that.data.show) {
              // add页面
                that.setData({
                    choosedAddVaccinationCondition: tmp,
                    choosedAddVaccinationCondition:''
                })
              } else {
              // 卡片初始正面
                that.setData({
                    choosedVaccinationCondition: tmp,
                    choosedVaccinationCondition:''
                })
              }
            return
        }
        wx.request({
          url: app.globalData.prefixUrl + '/chong/else/vaccineType/type',
          data:{
              petType:petType
          },
          method:"GET",
          success(e){
              console.log("获取"+petType+"疫苗信息成功: ", e)
              console.log("e.date == null ? :"+ e.data == null)
              console.log("e.date:", e.data)
              let choosed = {}
              choosed.id = 0

            if (e.data != null && e.data != '') {
                choosed.name = '疫苗类型'
            } else {
                console.log("数据库中没有:"+petType+"的疫苗数据")
                choosed.name = '无疫苗'
            }
           
            if (!that.data.notUpdate) {
                // 更新页面
                that.setData({
                    conditionUpdateVaccinationList: e.data,
                    choosedUpdateVaccinationCondition: choosed,
                })
            } else if (that.data.show) {
                 // add页面
                that.setData({
                    conditionAddVaccinationList: e.data,
                    choosedAddVaccinationCondition: choosed
                })
            } else {
                // 卡片初始正面 + update
                let firstData = [{}]
                firstData[0].name = '选择所有'
                firstData[0].id = 0 
                that.setData({
                    conditionVaccinationList: firstData.concat(e.data),
                    choosedVaccinationCondition: choosed
                })
           }
          }
        })
    },

    // 初始化数据
    initializeDate(){
        var that = this
    
        // 用户宠物数据, 下拉框
        wx.request({
          url: app.globalData.prefixUrl + '/chong/pet/pet/user/' + app.globalData.userId,
          method:"GET",
          success(e){
            console.log("获取当前用户宠物数据成功: ",e)
            let pet = e.data[0]
            let choosedPetCondition = {}
            choosedPetCondition.id = pet.id
            choosedPetCondition.nickname = pet.nickname
            choosedPetCondition.type = pet.type
            that.setData({
                conditionPetList: e.data,
                conditionAddPetList: e.data,
                choosedPetCondition,
            })
            that.getPetRelatedVaccination(pet.type);
          },
          fail(e){
            console.log("获取当前用户宠物数据失败: ",e)
          }
        })

        that.searchSubmit()
    },    

})